package org.yufan.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.yufan.bean.Item;
import org.yufan.bean.ItemDesc;
import org.yufan.constant.ItemConstant;
import org.yufan.service.ItemDescService;
import org.yufan.service.ItemService;
import org.yufan.utils.HttpClientUtil;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.util.Date;
import java.util.List;

@Service
public class ItemServiceImpl extends BaseServiceImpl<Item> implements ItemService {

    @Autowired
    private ItemDescService itemDescService;

    @Autowired
    private JmsTemplate jmsTemplate;


    public void addItem(Item item, String desc) {
        item.setCreated(new Date());
        item.setUpdated(item.getCreated());
        item.setStatus(ItemConstant.ITEM_SATATE_LOW);
        this.save(item);

        ItemDesc itemDesc=new ItemDesc();
        itemDesc.setItemId(item.getId());
        itemDesc.setItemDesc(desc);
        itemDesc.setCreated(item.getCreated());
        itemDesc.setUpdated(item.getCreated());
        itemDescService.save(itemDesc);
    }

    @Override
    public void updateItem(Item item, String desc) {
        item.setUpdated(new Date());
        this.update(item);

        //通知前台系统删除缓存
        //HttpClientUtil.doGet("http://www.yufan.com/api/item/cache/delete/"+item.getId());
        jmsTemplate.send(new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(item.getId()+"");
            }
        });


        ItemDesc itemDesc=new ItemDesc();
        itemDesc.setItemId(item.getId());
        itemDesc.setUpdated(item.getCreated());
        itemDesc.setItemDesc(desc);
        itemDescService.update(itemDesc);
    }

    @Override
    public void reshelf(List<Long> ids) {

        for (Long id:ids) {
            Item item = this.queryById(id);
            item.setStatus(ItemConstant.ITEM_SATATE_NORMAL);
            this.update(item);
        }

    }


}
